package com.netty8018.nettytask;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author liyanhao
 * @Date 2023-02-04 22:08
 * 1.自定义一个handler 需要继续netty规定好某个handlerAdapter规范
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    //读取实际的数据


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //比如这里我们又一个非常耗时的业务 ->异步执行->提交该channel对应的
        //NIOEventLoop的taskQueue
        //解决方案 1 用户自定义的普通任务
        ctx.channel().eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                try{
                    TimeUnit.SECONDS.sleep(5);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端处理很耗时", StandardCharsets.UTF_8));
                    System.out.println("channel codc=" + ctx.channel().hashCode());
                } catch (InterruptedException e) {
                    System.out.println("发生异常:"+e);
                }
            }
        });
        ctx.channel().eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(5);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello 客户端处理中", CharsetUtil.UTF_8));
                    System.out.println("channel codc=" + ctx.channel().hashCode());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {

                }
            }
        });

        //解决方案2 用户自定义任务->该任务是提交到 schuledTaskQueue中
        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(5);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello 客户端-4", StandardCharsets.UTF_8));
                    System.out.println("channel code=" + ctx.channel().hashCode());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, 5, TimeUnit.SECONDS);
        System.out.println("going on ...");

    }

    //读取数据完毕

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //writeAndFlush 是write+flush
        //数据写入到缓存 并刷新
        //一般讲 我们对这个发送的数据进行编码
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello 客户端 1", CharsetUtil.UTF_8));
    }

    //异常处理需要关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}
